package http_cookie

import (
	"io"
	"net/http"
)

// 启动 http 服务器
func RunCookie() {

	http.HandleFunc("/", setCookie)
	http.HandleFunc("/add", setCookie2)
	http.HandleFunc("/get", getCookie)
	http.HandleFunc("/del", delCookie)

	http.ListenAndServe(":80", nil)

}

// 第一种设置
func setCookie(w http.ResponseWriter, r *http.Request) {

	// 设置 cookie 的参数
	ck := &http.Cookie{
		Name:   "userid",
		Value:  "123456",
		MaxAge: 120,
	}

	// 进行写入(设置)cookie
	http.SetCookie(w, ck)

	// 打印输出
	w.Write([]byte("设置 cookie：userid"))

}

// 第二种设置
func setCookie2(w http.ResponseWriter, r *http.Request) {

	// 设置 cookie 的参数
	ck1 := &http.Cookie{
		Name:   "age",
		Value:  "18",
		MaxAge: 120,
	}

	ck2 := &http.Cookie{
		Name:   "sex",
		Value:  "1",
		MaxAge: 120,
	}

	// 进行写入(设置)cookie - 第一次是 设置
	w.Header().Set("Set-Cookie", ck1.String())
	// 进行写入(追加)cookie - 第二次是 追加
	w.Header().Add("Set-Cookie", ck2.String())

	// 打印输出
	w.Write([]byte("设置 cookie：age sex"))

}

// 删除 Cookie
func delCookie(w http.ResponseWriter, r *http.Request){

	ck := &http.Cookie{
		Name:   "sex",
		MaxAge: -1,
	}
	// 进行写入(设置)cookie
	http.SetCookie(w, ck)

	// 打印输出
	w.Write([]byte("删除 cookie：sex"))

}

// 获取 cookie
func getCookie(w http.ResponseWriter, r *http.Request) {

	w.Write([]byte("<html>"))

	// 获取 cookie
	userid, err := r.Cookie("userid")
	if err != nil {
		io.WriteString(w, err.Error())
		return
	}
	w.Write([]byte("userid：" + userid.Value + "<br>"))

	//
	h := r.Header["Cookie"]
	for _, v := range h {
		w.Write([]byte(v + "<br>"))
	}

	w.Write([]byte("</html>"))

}
